package com.tangula.web.kashine.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.nimbusds.oauth2.sdk.util.StringUtils;
import com.tangula.controller.ReturnRespController;
import com.tangula.core.Context;
import com.tangula.core.Controller;
import com.tangula.web.config.auth.Ignore;
import com.tangula.web.kashine.entity.BaseRespEntity;
import com.tangula.web.kashine.entity.ImageUploadForm;
import com.tangula.web.kashine.entity.ImageUploadResp;

@RestController
@RequestMapping("/imageController")
public class ImageController implements Controller<Context>, ReturnRespController, AuthController {

	public static final String KASHINE_IMAGE = "kashine_image";

	@RequestMapping(value = "/upload", consumes = "application/json", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<ImageUploadResp>> upload(@RequestBody ImageUploadForm image) {
		ImageUploadResp resp = new ImageUploadResp();

		if (image != null) {
			String b64 = image.getB64();
			if (StringUtils.isNotBlank(b64)) {

				byte[] data = Base64.decodeBase64(b64);

				String file_name = DigestUtils.md5Hex(data);

				String home = System.getProperty("user.home");

				File parent_file = new File(home, KASHINE_IMAGE);

				if (!parent_file.exists()) {
					if (!parent_file.mkdirs()) {
						logWarn("upload image dir can't be create:"+parent_file.getPath());
						return returnSuccess(resp);
					}
				}
				
				File image_file = new File(parent_file, file_name);

				if (!image_file.exists()) {
					try (FileOutputStream fos = new FileOutputStream(image_file)) {
						fos.write(data);
						fos.flush();
					} catch (FileNotFoundException e) {
						logError(e);
					} catch (IOException e) {
						logError(e);
					}
				}

				resp.setImageId(file_name);
			}
		}
		
		logInfo("upload image resp:"+JSONObject.toJSONString(resp));

		return returnSuccess(resp);
	}

	

}
